package learnJava1.JDBC.CRUDUtils;

import learnJava1.JDBC.domain.JDBCUnits;

import java.lang.reflect.Field;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class JDBCselect {
    public static <T> List<T> getSelcct(Class<T> tclass , String sql ,Object ...args){
        Connection c = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        ArrayList<T> list = new ArrayList<>();
        try {
            c = JDBCUnits.getConnectino();
            ps = c.prepareStatement(sql);

            for(int i=0;i< args.length;i++){
                ps.setObject(i+1,args[i]);
            }

            ResultSetMetaData rsmd = rs.getMetaData();
            int columnCount = rsmd.getColumnCount();
            while(rs.next()){
                T t = tclass.newInstance();
                for(int i= 0;i<columnCount;i++){
                    Object c0 = rs.getObject(i+1);
                    String columnLable = rsmd.getColumnLabel(i+1);
                    Field field = tclass.getDeclaredField(columnLable);
                    field.setAccessible(true);
                    field.set(t,c0);
                }
                list.add(t);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            JDBCUnits.close(c,ps,rs);
        }
        return list;
    }
}
